<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>路由传参</title>
</head>

<body>
  <div id="app">
    <!-- 
      http://localhost:8080/user/1001     路径参数,参数作为路径的一部分
      http://localhost:8080/user?id=1001  路径拼接，参数作为字符串拼接进来
     -->
    <h1>声明式导航 - 传参</h1>
    <!-- 正确写法 -->
    <router-link to="/login?id=1001&username=zhangsan">登录 -路径字符串</router-link>|
    <!-- 错误写法:如果参数是按照如下写法定义,那么无法匹配/login路径，因为路径层级不一样 -->
    <!-- <router-link to="/login/1001/zhangsan">登录 -路径字符串</router-link>| -->
    <!-- query配置项的内容，编译之后，其实和上面类似 -->
    <router-link :to="{path:'/register',query:{id:1002,username:'lisi'}}">注册 - 配置对象 - path</router-link>|
    <router-link :to="{name:'center',query:{id:1003,username:'王五'}}">中心 - 配置对象 - name</router-link>|

    <h1>编程式导航 - 传参</h1>
    <button type="button" @click="doIndex">首页</button>
    <button type="button" @click="doWelcome">欢迎</button>
    <router-view></router-view>
  </div>

  <template id="login">
    <div>
      <h2>我是登录组件</h2>
      <p>{{$route.query.username}}</p>
    </div>
  </template>

  <template id="register">
    <div>
      <h2>我是注册组件</h2>
      <p>{{$route.query.username}}</p>
    </div>
  </template>

  <template id="center">
    <div>
      <h2>我是中心组件</h2>
      <p>{{$route.query.username}}</p>
    </div>
  </template>

  <script src="../js/vue.js"></script>
  <script src="../js/vue-router.js"></script>
  <script>
    // 定义组件
    let Login = {
      template: '#login'
    }
    let Register = {
      template: '#register'
    }
    let Index = {
      template: `<div><h2>我是首页组件</h2></div>`
    }
    let Welcome = {
      template: `<div><h2>我是欢迎组件</h2></div>`
    }
    let Center = {
      template: '#center'
    }

    // 定义路由列表
    let routes = [{
        path: '/login',
        component: Login
      },
      {
        path: '/register',
        component: Register
      },
      {
        path: '/index',
        component: Index
      },
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/center',
        name: 'center',
        component: Center
      },
    ]

    // 定义路由器
    let router = new VueRouter({
      routes
    })

    // 创建Vue实例
    const vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        doIndex() {
        // 三种方式
        //  this.$router.push('/login?id=1004&username=马六')
        //  this.$router.push({path:'/register',query:{id:1002,username:'小黑'}})
         this.$router.push({name:'center',query:{id:1003,username:'小白'}})
        },
        doWelcome() {

        }
      },
      router: router //绑定路由器
    })
  </script>
</body>

</html>